package com.primeton.eos.oss.model.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.primeton.eos.oss.model.dto.ProjectFileDto;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipFileProcessor {

    public static void main(String[] args) {
        // 目标文件
        String zipFilePath = "D:\\test\\2024-10-15.zip";
        // 解压后路径
        String extractRootPath = "D:\\test\\bendi";

        try {

            // 使用 ZipInputStream 获取文件名
           Map<String,String> cacheMap=new HashMap();
            // 解压 ZIP 文件
            unzip(zipFilePath, extractRootPath.toString(),cacheMap);
            Path targetDir = Paths.get(extractRootPath, cacheMap.get("fileName").replace(".zip", ""));
            // 解析 data.txt，建立 ID 和文件的关系
            List<ProjectFileDto> projectFileDtos = new ArrayList<>();
            Map<String, String> moduleMap=new HashMap<>();
            parseDirectory(targetDir.toString(), projectFileDtos,moduleMap);
            for (Map.Entry<String, String> entry : moduleMap.entrySet()) {
                System.out.println(entry.getKey() + ": " + entry.getValue());
            }
            // 输出结果
            for (ProjectFileDto dto : projectFileDtos) {
                if (!moduleMap.isEmpty() && StrUtil.isNotBlank(moduleMap.get(dto.getModule()))){
                    dto.setModuleName(moduleMap.get(dto.getModule()));
                }
                System.out.println(dto.getId()+">>>>>"+dto.getModuleName()+">>>>"+dto.getFilePath()+">>>>>>"+dto.getFileName());
            }
            cacheMap.clear();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void unzip(String zipFilePath, String destDir,Map<String,String> cacheMap) throws IOException {
        try  {
            InputStream inputStream = new FileInputStream(zipFilePath);
            Charset gbk = Charset.forName("GBK");
            ZipInputStream zipInputStream = new ZipInputStream(inputStream,gbk);
            ZipEntry entry;
            while ((entry = zipInputStream.getNextEntry()) != null) {
                if (StrUtil.isBlank(cacheMap.get("fileName"))){
                    cacheMap.put("fileName",entry.getName());
                }
                File file = new File(destDir, entry.getName());
                if (entry.isDirectory()) {
                    file.mkdirs();
                } else {
                    file.getParentFile().mkdirs();
                    try (OutputStream outputStream = new FileOutputStream(file)) {
                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = zipInputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                    }
                }
                zipInputStream.closeEntry();
            }
        }catch (Exception ex){

        }
    }

    private static void parseDirectory(String dirPath, List<ProjectFileDto> projectFileDtos, Map<String, String> moduleMap) throws IOException {
        Files.walk(Paths.get(dirPath)).forEach(path -> {
            if (Files.isRegularFile(path)) {
                if (path.getFileName().toString().endsWith(".txt")) {
                    handleDataFile(dirPath,path, projectFileDtos,moduleMap);
                }
            } else if (Files.isDirectory(path)) {
                String parentId = getParentIdFromDirectory(path); // 假设父文件夹名称为 ID
                if (StrUtil.isNotBlank(parentId) && isNumeric(parentId)) {
                    collectFilesUnderDirectory(path, parentId, projectFileDtos);
                }
            }
        });
    }

    private static String getParentIdFromDirectory(Path directory) {
        try {
            return directory.getFileName().toString();
        } catch (NumberFormatException e) {
            return null; // 不能解析为 ID 的情况
        }
    }

    private static void collectFilesUnderDirectory(Path directory, String parentId, List<ProjectFileDto> projectFileDtos) {
        StringBuilder fileNames = new StringBuilder();

        try {
            // 收集该目录下的所有文件名
            Files.list(directory).forEach(filePath -> {
                if (Files.isRegularFile(filePath)) {
                    if (fileNames.length() > 0) {
                        fileNames.append(";"); // 多个文件用分号隔开
                    }
                    fileNames.append(filePath.getFileName().toString());
                }
            });

            // 查找对应 parentId 的 ProjectFileDto
            for (ProjectFileDto dto : projectFileDtos) {
                if (dto.getId().equals(parentId)) { // 假设 ProjectFileDto 有 getId() 方法
                    dto.setFileName(fileNames.toString()); // 假设有 setFileNames() 方法来更新文件名
                    break; // 找到后可以退出循环
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void handleDataFile(String rootPath,Path dataFilePath, List<ProjectFileDto> projectFileDtos, Map<String, String> moduleMap) {
        try {
            String jsonData = new String(Files.readAllBytes(dataFilePath), Charset.forName("GBK"));
            parseJson(rootPath,jsonData, projectFileDtos,moduleMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void parseJson(String rootPath,String jsonData, List<ProjectFileDto> projectFileDtos,  Map<String, String> moduleMap) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode rootNode = objectMapper.readTree(jsonData);
            JsonNode dataArray = rootNode.path("data");
            JsonNode moduleNode = rootNode.path("description").path("module");
            for (JsonNode item : dataArray) {
                String id = item.path("id").asText();;
                String module = item.path("module").asText();
                String fsProNumber = item.path("fsProNumber").asText();
                String annex = item.path("annex").asText();

                // 取父级目录
                String filePath = rootPath+"/"+annex;
                // 找到与该 ID 相关的文件名
                // 这里需要根据项目 ID 关联文件名，可以调整逻辑
                projectFileDtos.add(new ProjectFileDto(id, module, fsProNumber, "",filePath));
            }
            if (moduleMap.isEmpty()){
                moduleMap.putAll(objectMapper.convertValue(moduleNode, Map.class));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static boolean isNumeric(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        for (char c : str.toCharArray()) {
            if (!Character.isDigit(c)) {
                return false;
            }
        }
        return true;
    }



}


